package com.example.listgame;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


import pl.com.salsoft.sqlitestudioremote.SQLiteStudioService;

public class MainActivity extends AppCompatActivity {

    private DBOpenHelper dbOpenHelper;  //声明DBOpenHelper对象
    private EditText mUsername,mPassword;
    private Button mLogin,mCreate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SQLiteStudioService.instance().start(this);
        dbOpenHelper = new DBOpenHelper(MainActivity.this,"db_userinfo.db",null,1);  //实例化DBOpenHelper对象，用来创建数据库
        mUsername = findViewById(R.id.username);
        mPassword = findViewById(R.id.password);
        mLogin = findViewById(R.id.login);
        mCreate = findViewById(R.id.create);
        mLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String um = mUsername.getText().toString(); //获取用户昵称
                String pwd = mPassword.getText().toString(); //获取用户密码
                if (um.equals("") || pwd.equals("")) {     //如果填写的昵称或密码为空时
                    Toast.makeText(MainActivity.this,"昵称或密码不能为空",Toast.LENGTH_SHORT).show();
                }else {
                    SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
                    Cursor cursor = db.query("UserInfo", null, "username=? and password=?", new String[]{um, pwd}, null, null, null);
                    if (cursor != null && cursor.getCount() >= 1) {
                        Intent intent = new Intent(MainActivity.this, CheckLevelActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putString("username",um);
                        intent.putExtras(bundle);
                        startActivity(intent);
                        cursor.close();
                    } else {
                        Toast.makeText(MainActivity.this, "用户名或密码错误", Toast.LENGTH_LONG).show();
                    }
                }
            }
        });
        mCreate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this,RegisterActivity.class);
                startActivity(intent);
            }
        });
    }

    protected void onDestroy() {
        super.onDestroy();
        if (dbOpenHelper!=null){
            dbOpenHelper.close();  //关闭数据库连接
        }
    }
}
